/*
 * @Author: liuying 247220246@qq.com
 * @Date: 2025-03-24 16:24:40
 * @LastEditors: liuying 247220246@qq.com
 * @LastEditTime: 2025-04-21 18:18:56
 * @FilePath: \my-book-react\src\pages\search\compoments\searchHistory\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import React from 'react';
import cx from 'classnames';
import { Space } from '@/bases';
import { HISTORY_SEARCH_KEY } from '@/pages/search/constants';
import { deleteHistory, clearHistory, setHistory } from '@/pages/search/utils';
import { setSearchMode, setSearchKeyword } from '@/stores/slices/searchSlice';
import { searchActions } from '@/pages/search/stores';
import useReadLocalStorage from '@/hooks/useReadLocalStorage';
import { useAppSelector, useAppDispatch } from '@/stores';
import { px2rem } from '@/utils/unit';
import { setUrlParams } from '@/utils/url';
import styles from './index.module.scss';

// 定义一个名为SearchHistory的React组件，使用React.memo进行优化
const SearchHistory: React.FC = React.memo(() => {
  const dispatch = useAppDispatch();
  // 使用useAppSelector获取searchMode的值
  const searchMode = useAppSelector<boolean>((state) => state.search.searchMode);
  // 使用useReadLocalStorage获取historyList的值
  const historyList = useReadLocalStorage<string[]>(HISTORY_SEARCH_KEY);
  console.log('historyList', historyList);

  // 定义一个空函数onClear
  const onClear = () => {
    clearHistory();
  };
  const onSearch = (e: React.MouseEvent) => {
    const keyword = (e.target as HTMLElement).dataset['keyword'] as string;
    setUrlParams([['keyword', keyword]], '/search');
    dispatch(searchActions.setSearchMode(true));
    dispatch(searchActions.setSearchKeyword(keyword));
  };
  const onDelete = (e: React.MouseEvent) => {
    const name = (e.target as HTMLElement).dataset['name'] as string;
    deleteHistory(name);
  };
  // 返回一个div，包含一个header，header中包含一个title和一个icon-delete
  return (
    <div className={cx(styles.searchHistory, { [styles.hidden]: searchMode })}>
      <div className={styles.header}>
        <div className={styles.title}>搜索历史</div>
        <i className="icon-delete" onClick={onClear} />
      </div>
      <div className={styles.list}>
        <Space direction="vertical" gap={px2rem(20)}>
          {Array.isArray(historyList) &&
            historyList.map((item) => (
              <div className={styles.listItem} key={item}>
                <div className={styles.name} data-keyword={item} onClick={onSearch}>
                  {item}
                </div>
                <i className="icon-close" data-name={item} onClick={onDelete} />
              </div>
            ))}
        </Space>
      </div>
    </div>
  );
});

export default SearchHistory;
